package com.example.bluetoothlib.model;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.concurrent.LinkedBlockingQueue;

import android.bluetooth.BluetoothSocket;
import android.util.Log;


public class BTConnectionManager
{
	LinkedBlockingQueue<String> message;
	OutputStream outputStream;
	InputStream inputStream;
	IBTEventHandler eventHandler;
	Thread readThread;
	public BTConnectionManager()
	{
		message=new LinkedBlockingQueue<String>();
	}

	public void establishConnection(BluetoothSocket socket) 
	{
		Log.d("connection established", "connection established");
		try {
			outputStream=socket.getOutputStream();
			inputStream=socket.getInputStream();

			readThread=new Thread(new Runnable() 
			{
				
				@Override
				public void run() 
				{
					while(true)
					{
						byte[] buffer=new byte[1024];
						try {
							int tmp=inputStream.read(buffer);
							if(tmp!=-1)
							{
								String string=new String(buffer);
								if(null!=string&&!string.equals(""))
								{
									message.put(string);
								}
							}
						} catch (IOException e) {
							e.printStackTrace();
						} catch (InterruptedException e) {
							e.printStackTrace();
						}
					}
				}
			});
			readThread.start();
			eventHandler.onConnectionEstablished();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public String readString() {
		try {
			Log.d("Read string", "trying to read a string");
			return message.take();
		} catch (InterruptedException e) {
			e.printStackTrace();
			return "";
		}
	}
	
	public void writeString(String msg) 
	{
		try {
			Log.d("write string", "trying to write a string done");
			outputStream.write(msg.getBytes());
			outputStream.flush();
			Log.d("write string", "write a string done");
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public void setEventHandler(IBTEventHandler event)
	{
		this.eventHandler=event;
	}
}
